<template>
  <div style="width: 100%; height: 400px;">
    <div :id="id" style="width: 100%; height: 300px;"></div>
    <div :id="mousePositionId"></div>
    <el-button @click="zoomToLayer">缩放至图层</el-button>
  </div>
</template>

<script>
import globalmf from '@/utils/Global/GlobalMapFunction'
export default {
  name: "mapService",
  data(){
    return{
      id:"mapServiceMap",
      mousePositionId:"mapServiceMousePosition",
      map:null,
      layer:null
    }
  },
  props:{
    config:{
      type:Object,
      default(){
        return {
          url:"",
          type:-1,
          sys:4326,
          name:"",
          id:"testLayer",
          zIndex:1
        }
      }
    }
  },
  mounted() {
    globalmf.initx2js();
    this.initMap();
  },
  methods:{
    initMap(){
      let that = this;
      let prj = 'EPSG:4326';
      if (that.config.sys) {
        prj = that.config.sys;
      }

      let topResolution;
      let resolutions = [];
      if (that.config.type != 2) {
        that.map = new ol.Map({
          target: that.id,
          // controls: ol.control
          //     .defaults({attributionOptions: {collapsed: false}})
          //     .extend([new ol.supermap.control.Logo()]),

          controls: ol.control.defaults({
            attributionOptions: ({
              collapsible: false//2022年2月28日 LQ 很诡异，map的一堆control初始都有问题。
            })
          }).extend([
            new ol.control.MousePosition({//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
              coordinateFormat: ol.coordinate.createStringXY(4),
              className: 'custom-mouse-position',
              target: that.mousePositionId,
              undefinedHTML: '&nbsp;'
            }),
            new ol.control.ScaleLine(),//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
          ]),
          view: new ol.View({
            //center: [0, 0],
            //zoom: 2,
            //projection: prj
          })
        });
      } else {
        topResolution = 360.0 / 512;
        resolutions = [];
        for (let zoom = 0; zoom < 22; zoom++) {
          resolutions.push(topResolution / Math.pow(2, zoom));
        }
        that.map = new ol.Map({
          target: that.id,
          controls: ol.control.defaults({
            attributionOptions: ({
              collapsible: false//2022年2月28日 LQ 很诡异，map的一堆control初始都有问题。
            })
          }).extend([
            new ol.control.MousePosition({//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
              coordinateFormat: ol.coordinate.createStringXY(4),
              className: 'custom-mouse-position',
              target: that.mousePositionId,
              undefinedHTML: '&nbsp;'
            }),
            new ol.control.ScaleLine(),//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
          ]),
          view: new ol.View({
            // center: [116, 39],
            // zoom: 6,
            // projection: prj, //'EPSG:4326',
            // resolutions: resolutions
          })
        });
      }
      globalmf.addServiceToMap(that.map,that.config,null);
    },
    zoomToLayer(){
      let that = this;
      let layer = globalmf.getLayerById(that.map,that.config.id);
      let extent = [110, 42, 140, 53]; //= [110, 42, 140, 53]
      if (layer.getExtent()) {
        extent = layer.getExtent();
      } else if (layer.getSource() instanceof ol.source.WMTS) {
        extent = layer.getSource().tileGrid.extent_;
      } else if (layer.getSource() instanceof ol.source.Vector) {
        extent = layer.getSource().getExtent();
      }
      globalmf.zoomToExtent(that.map, extent);
    },
    CreateLayer(serviceUrl, serviceType, prjType, GetLayerFunc) {
      let layer = null;
      let url = serviceUrl;
      switch (serviceType) {
        case 1://rest
//                    if (prjType == 3857) {
//                        url = 'http://localhost:8090/iserver/services/map-world/rest/maps/World';
//                        //url = 'http://localhost:8090/iserver/services/map-world/rest/maps/World?prjCoordSys={"epsgCode":3857}';
//                    } else {
//                        url = 'http://localhost:8090/iserver/services/map-world/rest/maps/World';
//                    }
          //url = 'http://localhost:8090/iserver/services/map-world/rest/maps/World';
          layer = new ol.layer.Tile({
            source: new ol.source.TileSuperMapRest({
              url: url,
              wrapX: true,
              prjCoordSys: {"epsgCode": prjType}
            }),
          });
          GetLayerFunc(layer);
          break;
        case 3://wmtschina
        case 4://wmts100
          //url = "http://localhost:8090//iserver/services/map-china400/wmts100";
          fetch(url).then(function (response) {
            return response.text();
          }).then(function (text) {
            let parser = new ol.format.WMTSCapabilities();
            let result = parser.read(text);
            let options = ol.source.WMTS.optionsFromCapabilities(result, {
              layer: 'China',
              matrixSet: 'GoogleMapsCompatible_China'
            });
            layer = new ol.layer.Tile({
              opacity: 1,
              source: new ol.source.WMTS(options)
            });
            GetLayerFunc(layer);
          });
//                    var resolutions = new Array(17);
//                    var matrixIds = new Array(17);
//                    for (var z = 0; z < 17; ++z) {
//                        resolutions[z] = 156543.033928041 / Math.pow(2, z);
//                        matrixIds[z] = z;
//                    }
//                    layer = new ol.layer.Tile({
//                        opacity: 0.7,
//                        source: new ol.source.WMTS({
//                            url: url,
//                            layer: 'China',
//                            matrixSet: 'GoogleMapsCompatible_China',
//                            format: 'image/png',
//                            projection: 'EPSG:3857',
//                            tileGrid: new ol.tilegrid.WMTS({
//                                origin: [-2.0037508342787E7, 2.0037508342787E7],
//                                extent: [-2.0037508342787E7, -2.0037508342787E7, 2.0037508342787E7, 2.0037508342787E7],
//                                resolutions: resolutions,
//                                matrixIds: matrixIds
//                            }),
//                            style: 'default'
//                        })
//                    });
          break;
        case 5://wms111
        case 6://wms130
          //url = "http://localhost:8090//iserver/services/map-china400/wms111/China";
          layer = new ol.layer.Tile({
            opacity: 0.7,
            source: new ol.source.TileWMS({
              url: url,
              params: {
                'LAYERS': 'China',
                'FORMAT': 'image/png'
              }
            }),
          });
          GetLayerFunc(layer);
          break;
      }
    },
    CreateVectorLayer(serviceUrl, prjType, map, GetLayerFunc) {
      let layer = null;
      let url = serviceUrl;
      //url = "http://localhost:8090/iserver/services/map-china400/restjsr/v1/vectortile/maps/China_4326/style.json";

//                    var container = document.getElementById('popup');
//                    var content = document.getElementById('popup-content');
//                    info = new ol.control.Control({
//                        element: container
//                    });
//                    info.setMap(map);
//                    map.addControl(info);
      let format = new ol.format.MVT({
        featureClass: ol.Feature
      });
      let style = new ol.supermap.MapboxStyles({
        style: url,
        // source: 'China_4326',
        map: map
      });
      style.on('styleloaded', function () {
        layer = new ol.layer.VectorTile({
          declutter: true,
          source: new ol.source.VectorTileSuperMapRest({
            style: url,
            projection: 'EPSG:4326',
            // source: 'China_4326',
            format: format
          }),
          style: style.getStyleFunction()
        });
        GetLayerFunc(layer);
      });
    }
  },
}
</script>

<style scoped>

</style>
